<?php

namespace app\ports\controller\publics;

use think\Db;

/**
 * 计算模板
 */
class Template
{

	protected static $instance;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config = [
		"prefix" 	=> "fd_",
		"pro" 		=> "bonus_product",
		"sta" 		=> "bonus_stands",
		"lev" 		=> "bonus_level",
		"cash" 		=> "bonus_cash"
	];

	/**
	 * 获取实例对象
	 * @return Template|object
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 查看产品是否可计算
	 * @return boolean
	 */
	public function _check_calc_product_template($pros, $card, $trans, $route)
	{
		if (!empty($pros) && !empty($card) && !empty($trans) && !empty($route)) {
			$find = Db::name($this->config["pro"])->where("pro_id = '{$pros}' and isStatus = 1")->field("pro_id,card_ids,trans_ids,route_ids")->find();
			if ($find) {
				$ex_cards = explode(",", $find["card_ids"]);
				if (in_array($card, $ex_cards)) {
					$cardsCheck = true;
					if (!empty($find["trans_ids"])) {
						$ex_trans = explode(",", $find["trans_ids"]);
						if (!in_array($trans, $ex_trans)) $cardsCheck = false;
					}
					$routeCheck = true;
					if (!empty($find["route_ids"])) {
						$ex_route = explode(",", $find["route_ids"]);
						if (!in_array($route, $ex_route))  $routeCheck = false;
					}
					if ($cardsCheck && $routeCheck)  return true;
				}
			}
		}
		return false;
	}

	/**
	 * 获取达标模板
	 * @param  $nums 基础达标个数
	 * @return array|bool
	 */
	public function stands_calc($nums)
	{
		if (!empty($nums)) {
			$query = Db::table($this->config["prefix"] . $this->config["sta"] . " s," . $this->config["prefix"] . $this->config["lev"] . " l")
				->field("s.id,l.id lev,l.code,l.title,l.code,(s.tranAmt * 10000) money,s.nums")
				->where("s.lev_id = l.id and  s.state = 1  and nums <= {$nums}")->select();
			return $query;
		}
		return false;
	}

	/**
	 * 分红达标模板匹配查看
	 * 
	 * @return bool
	 */
	public function _check_use_stands($code, $nums)
	{
		if (!empty($code) && !empty($nums)) {
			$lev_id = Db::name($this->config["lev"])->where("code = '{$code}'")->value("id");
			if ($lev_id) {
				$stands_nums = Db::name($this->config["sta"])->where("lev_id = " . $lev_id)->value("nums");
				if ($stands_nums) {
					if ($stands_nums <= $nums) return true;
				}
			}
		}
		return  false;
	}

	/**
	 * 分红计算模板
	 * @return array|bool
	 */
	public function bonus_calc()
	{
		$query = Db::table($this->config["prefix"] . $this->config["cash"] . " c," . $this->config["prefix"] . $this->config["lev"] . " l")
			->where("c.lev_id = l.id")
			->field("c.lev_id,c.radio,l.code lev_code")
			->select();
		if ($query) return $query;
		return false;
	}
}
